#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pygtk
pygtk.require('2.0')
import gtk
import gnome.ui
import gnomeapplet
import gtk.glade
import sys

import gdata.calendar.service
import gdata.service
import atom.service
import gdata.calendar

from gcapplet import globals
from gcapplet import events
from gcapplet import auth

#import globals
#import events
#import auth

class gcapplet:
	auth_ok = False
	def __init__(self, applet, iid):
		self.applet = applet
		self.calendar_on = 0
		self.popup_menu_init()
		self.init_widgets()
		self.init_signals()
		self.glade_init()
		self.applet.show_all()
		self.date = None
	
	# Инициализация главных виджетов
	def init_widgets(self):
			#icon setting
		self.icon_pixbuf = gtk.gdk.pixbuf_new_from_file(globals.IMAGES_DIR + '/gcapplet.png')
		#self.icon_pixbuf = gtk.gdk.pixbuf_new_from_file('gcapplet.png')
		
		icon_pixbuf_scaled = self.icon_pixbuf.scale_simple(24, 24, gtk.gdk.INTERP_BILINEAR)
		self.icon = gtk.Image()
		self.icon.set_from_pixbuf(icon_pixbuf_scaled)
			#event setting
		self.event_box = gtk.EventBox()
		self.event_box.add(self.icon)
			#main box
		self.box = gtk.HBox()
		self.box.add(self.event_box)
			# applet -> box -> event_box -> icon
		self.applet.add(self.box)
	
	# Инициализация контекстного меню
	def popup_menu_init(self):
		self.popup_xml = '''
		<popup name='button3'>
			<menuitem name='item_1' verb='Authorization'
					_label='Authorization'/>
			<menuitem name='item_2' verb='About'
					pixtype='stock' stockid='gtk-about'/>
		</popup>
		'''
		self.popup_verbs = [
							('Authorization', self.on_popup_auth), 
							('About', self.on_popup_about)
							]
	
	# Сигналы главных виджетов соедияются с коллбеками
	def init_signals(self):
		self.event_box.connect("button-press-event", self.icon_pressed)
		self.icon_signals = {
				1: self.on_icon_left,
				2: lambda: None,
				3: self.on_icon_right
					}
	
	# Обработчик события "нажатие на иконку"
	def icon_pressed(self, widget, event):
		self.icon_signals[event.button]()
	
	# Левая кнопка
	def on_icon_left(self):
		if self.calendar_on:
			self.hide_calendar()
		else:
			self.show_calendar()
	
	# Средняя кнопка
	def on_icon_middle(self):
		return	
	
	# Правая кнопка
	def on_icon_right(self):
		self.applet.setup_menu(self.popup_xml, self.popup_verbs)
	
	# Отобразить окно календаря
	def show_calendar(self):
		#loc = self.applet.get_allocation()
		#self.show_debug_info(loc.x)
		#print self.applet.translate_coordinates(self.box, 5,5)
		#parent = self.applet.get_parent()
		#parent =  self.applet.get_parent_window()
		#a = gtk.gdk.Window.get_root_origin(parent)
		#self.show_debug_info(a)
		self.calendar_window.move(self.box.allocation.x + 800,
						self.icon.allocation.y + self.icon.allocation.height)
		self.calendar_window.show_all()
		self.calendar_on = 1
		if self.auth_ok:
			self.edit_but.set_sensitive(True)
			#self.authorization
		else:
			self.edit_but.set_sensitive(False)
	
	# Скрыть окно календаря
	def hide_calendar(self):
		self.calendar_window.hide_all()
		self.calendar_on = 0
	
	# Инициализация Glade
	def glade_init(self):
		glade_file =  globals.DATA_DIR + '/calendar.glade'
		#glade_file = 'calendar.glade'
		self.glade_tree = gtk.glade.XML(glade_file)
		dict = {'on_calendar_day_selected' : self.on_calendar_day_selected, 
					'on_edit_button_clicked' : self.on_edit_button_clicked,
					}
		self.glade_tree.signal_autoconnect(dict)
		
		self.calendar_window = self.glade_tree.get_widget('calendar_window')			
		self.calendar = self.glade_tree.get_widget('calendar')
		self.edit_but = self.glade_tree.get_widget('edit_button')
		self.edit_but.set_sensitive(False)
	
	# Пункт меню "О программе"
	def on_popup_about(self, widget, data):
		about = gnome.ui.About('Google Calendar Applet', globals.VERSION, '© 2010 Serafim Nenarokov, Olga Uhina',
												'Google Calendar services integration for Gnome environment.', 
												['Serafim Nenarokov <serafim.nenarokov@gmail.com>', 
												'Olga Uhina <olga.uhina@gmail.com>',
												'Anna Nevzorova <Luxray777@gmail.com>'],
												 None, 'translation', self.icon_pixbuf)
		about.set_icon(self.icon_pixbuf)
		about.show()
	
	# Пункт меню - авторизация
	def on_popup_auth(self, widget, data):
		# Передаем информацию об авторизации по нажатии на кнопку Ok
		def button_callback(widget):
			self.auth_ok = self.authorization.is_ok
		# Если календарь открыт - сворачиваем
		if self.calendar_on:
			self.hide_calendar()
		self.authorization = auth.auth()
		self.authorization.ok_button.connect('clicked', button_callback, )
    
	def on_calendar_day_selected(self, widget):
		(year, month, day) = widget.get_date()
		if day<10:
			date = str(year) + "-0" + str(month+1) + "-" + "0" + str(day) 
		else:
			date = str(year) + "-0" + str(month+1) + "-" + str(day)	
		self.date = date

		# Кнопка - запуск редактирования события
	def on_edit_button_clicked(self, widget):
		print self.authorization.login
		l = self.authorization.login
		ui = events.EventWindow(self.date, self.authorization.login)
		
		# Всплывающее окошко для вывода любой информации
	def show_debug_info(self, info):
		wnd = gtk.Window(gtk.WINDOW_TOPLEVEL)
		wnd.set_default_size(200, 40)
		lbl = gtk.Label()
		lbl.set_text(str(info))
		wnd.add(lbl)
		wnd.show_all()


def applet_factory(applet, iid):
    gcapplet(applet, iid)
    return gtk.TRUE


if len(sys.argv) == 2 and (sys.argv[1] == '-w'):
    window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    window.connect('destroy', gtk.main_quit)
    window.set_title('Applet debug mode')
    window.set_default_size(500, 24)

    applet = gnomeapplet.Applet()
    applet_factory(applet, None)
    applet.reparent(window)

    window.show_all()
    gtk.main()

gnomeapplet.bonobo_factory("OAFIID:GoogleCalendarApplet_Factory",
						     gnomeapplet.Applet.__gtype__,
						     "hello", "0", applet_factory)

